var BASE_URL = document.scripts[document.scripts.length - 1].src.substring(0, document.scripts[document.scripts.length - 1].src.lastIndexOf("/") + 1);
layui.use(['form','colorpicker'], function () {
    var form = layui.form,
        $ = layui.jquery,
        upload = layui.upload,
        layer=layui.layer;
        laydate=layui.laydate;

    var colorpicker = layui.colorpicker;

    var verifyList = document.querySelectorAll("[lay-verify]");
    if (verifyList.length > 0) {
        $.each(verifyList, function (i, v) {
            var verify = $(this).attr('lay-verify');

            // todo 必填项处理
            if (verify === 'required'||verify === 'otherReq') {
                var label = $(this).parent().prev();
                if (label.is('label') && !label.hasClass('required')) {
                    label.addClass('required');
                }
                if ($(this).attr('lay-reqtext') === undefined && $(this).attr('placeholder') !== undefined) {
                    $(this).attr('lay-reqtext', $(this).attr('placeholder'));
                }
                if ($(this).attr('placeholder') === undefined && $(this).attr('lay-reqtext') !== undefined) {
                    $(this).attr('placeholder', $(this).attr('lay-reqtext'));
                }
            }

        });
    }
    
    form.on('submit(formpost)', function (data) {
       var loading = layer.load(2, {
            shade: [0.2, '#000']
        });
        var param = data.field;
        $.post(window.location.href, param, function (data) {
            layer.close(loading);
            if (data.code == 1) {
                layer.msg(data.msg, { icon: 1, time: 1000 }, function () {
                    layer.close(layer.index);
                    window.parent.location.reload();
                });
            } else {
                layer.close(loading);
                layer.msg(data.msg, { icon: 2, anim: 6, time: 1000 });
            }
        });
        return false;
    });

    var dateList = document.querySelectorAll("[data-date]");
    if (dateList.length > 0) {
        $.each(dateList, function (i, v) {
            var format = $(this).attr('data-date'),
                type = $(this).attr('data-date-type'),
                range = $(this).attr('data-date-range');
            if(type === undefined || type === '' || type ===null){
                type = 'datetime';
            }
            var options = {
                elem: this,
                type: type,
            };
            if (format !== undefined && format !== '' && format !== null) {
                options['format'] = format;
            }
            if (range !== undefined) {
                if(range === null || range === ''){
                    range = '-';
                }
                options['range'] = range;
            }
            laydate.render(options);
        });
    }

    var colorList = document.querySelectorAll("[data-color]");
    if (colorList.length > 0) {
        $.each(colorList, function (i, v) {
            var colorName = $(this).attr('data-color');

            var elem = "input[name='" + colorName + "']";
            var color='';

            if (elem !== undefined && elem !== '' && elem !== null&& $(elem).val()!='') {
                color = $(elem).val();
            }

            colorpicker.render({
                elem:this,
                color:color,
                done: function(color1){
                    $(elem).val(color1)

            }}
            );
        });
    }


    var uploadList = document.querySelectorAll("[data-upload]");

    if (uploadList.length > 0) {
        $.each(uploadList, function (i, v) {
            var exts = $(this).attr('data-upload-exts'),
                uploadName = $(this).attr('data-upload'),
                watermark = $(this).attr('data-watermark'),
                thumb = $(this).attr('data-thumb'),
                uploadType = $(this).attr('data-upload-type'),
                uploadNumber = $(this).attr('data-upload-number'),
                uploadSign = $(this).attr('data-upload-sign');
            exts = exts || init.upload_exts;
            uploadNumber = uploadNumber || 'one';
            uploadType = uploadType || '';
            watermark = watermark || 0;
            thumb = thumb || 0;
            uploadSign = uploadSign || '|';
            var elem = "input[name='" + uploadName + "']",
                uploadElem = this;

            // 监听上传事件
            upload.render({
                elem: this,
                url: '/api/ajax/upload.html',
                data:{'watermark':watermark,'upload_type':uploadType,'thumb':thumb},
                accept: 'file',
                exts: exts,
                // 让多图上传模式下支持多选操作
                multiple: (uploadNumber !== 'one') ? true : false,
                done: function (res) {
                    if (res.code === 1) {
                        var url = res.data.url;
                        if (uploadNumber !== 'one') {
                            var oldUrl = $(elem).val();
                            if (oldUrl !== '') {
                                url = oldUrl + uploadSign + url;
                            }
                        }
                        $(elem).val(url);
                        $(elem).trigger("input");
                        layer.msg(res.msg);
                    } else {
                        layer.msg(res.msg);
                    }
                    return false;
                }
            });

            // 监听上传input值变化
            $(elem).bind("input propertychange", function (event) {
                var urlString = $(this).val(),
                    urlArray = urlString.split(uploadSign),
                    uploadIcon = $(uploadElem).attr('data-upload-icon');
                uploadIcon = uploadIcon || "file";

                $('#bing-' + uploadName).remove();
                if (urlString.length > 0) {
                    var parant = $(this).parent('div');
                    var liHtml = '';
                    $.each(urlArray, function (i, v) {
                        liHtml += '<li><a><img src="' + v + '" data-image  onerror="this.src=\'' + BASE_URL + 'admin/images/upload-icons/' + uploadIcon + '.png\';this.onerror=null"></a><small class="uploads-delete-tip bg-red badge" data-upload-delete="' + uploadName + '" data-upload-url="' + v + '" data-upload-sign="' + uploadSign + '">×</small></li>\n';
                    });
                    parant.after('<ul id="bing-' + uploadName + '" class="layui-input-block layuimini-upload-show">\n' + liHtml + '</ul>');
                }

            });

            // 非空初始化图片显示
            if ($(elem).val() !== '') {
                $(elem).trigger("input");
            }
        });

        // 监听上传文件的删除事件
        $('body').on('click', '[data-upload-delete]', function () {
            var uploadName = $(this).attr('data-upload-delete'),
                deleteUrl = $(this).attr('data-upload-url'),
                sign = $(this).attr('data-upload-sign');
            var confirm = layer.confirm('确定删除？', function () {
                var elem = "input[name='" + uploadName + "']";
                var currentUrl = $(elem).val();
                var url = '';
                if (currentUrl !== deleteUrl) {
                    url = currentUrl.search(deleteUrl) === 0 ? currentUrl.replace(deleteUrl + sign, '') : currentUrl.replace(sign + deleteUrl, '');
                    $(elem).val(url);
                    $(elem).trigger("input");
                } else {
                    $(elem).val(url);
                    $('#bing-' + uploadName).remove();
                }
                layer.close(confirm);
            });
            return false;
        });
    }

    var editorList = document.querySelectorAll(".editor");
    if (editorList.length > 0) {
        $.each(editorList, function (i, v) {
            var $this = $(this);
            $this.hide();
            var editorId = $this.attr("name");
            $(this).before('<div  id="' + editorId + '"></div>');
            const editor = new wangEditor('#' + editorId);
            //由于IE浏览器不支持，暂时屏蔽。有需要的小伙伴可自行解开 云阳2021年6月1日
            if (!window.VBArray) {
                class CustomMenu extends wangEditor.BtnMenu {
                    constructor(editor) {
                        const $elem = wangEditor.$(`<div class="w-e-menu"><a href="javaScript:;" id="menu_y" class="">源</a></div>`)
                        super($elem, editor)
                    }

                    // 【源】点击事件
                    clickHandler() {
                        var editorHtml = editor.txt.html();
                        if ($("#menu_y").attr("class") == "active_y") {
                            $("#menu_y").attr("class", "")
                            editorHtml = editor.txt.text().replace(/&lt;/ig, "<").replace(/&gt;/ig, ">").replace(/&nbsp;/ig, " ");
                        } else {
                            $("#menu_y").attr("class", "active_y")
                            editorHtml = editorHtml.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;");
                        }
                        editor.txt.html(editorHtml);
                        editor.change && editor.change();
                    }

                    tryChangeActive() {
                        this.active();
                    }
                }

                // 注册菜单
                const customMenuKey = 'customMenuKey';
                editor.menus.extend('customMenuKey', CustomMenu);
                editor.config.menus = editor.config.menus.concat(customMenuKey);
            }
            //TODO 上传代码
            editor.config.uploadImgServer = '/api/ajax/editorUploadImg'
            editor.config.uploadFileName = 'file'
            editor.config.uploadImgHooks = {

                fail: function (xhr, editor, resData) {
                    console.log(resData.msg)
                },
                // 上传图片超时
                timeout: function (xhr) {
                    console.log('timeout')
                }
            }
            editor.config.uploadVideoServer ='/api/ajax/editorUploadFile'
            editor.config.uploadVideoName = 'file'
            editor.config.uploadVideoHooks = {

                fail: function (xhr, editor, resData) {
                    layer.msg(resData.msg);
                },
                // 上传图片超时
                timeout: function (xhr) {
                    console.log('timeout')
                }
            }
            editor.config.onchange = function (html) {
                // 第二步，监控变化，同步更新到 textarea
                if ($("#menu_y").attr("class") == "active_y") {
                    html = html.replace(/&lt;/ig, "<").replace(/&gt;/ig, ">").replace(/&nbsp;/ig, " ");
                }
                $this.val(html)
            }
            editor.create();
            editor.txt.html($this.val());
        });
    }

    $('body').on('click', '[layform-close]', function () {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index);
    });
})